#include "CameraVideoCapture.h"
#include "modules/video_capture/video_capture_factory.h"
#include <QDebug>

CameraVideoCapture::CameraVideoCapture(QObject *parent) : QObject(parent)
{

}

CameraVideoCapture::~CameraVideoCapture()
{
    destroy();
}

bool CameraVideoCapture::init(const int &iWidth, const int &iHeight, const int &iFPS, const QString &strID)
{
    qDebug() << strID;
    m_modulePtr = webrtc::VideoCaptureFactory::Create(strID.toLatin1().data());
    m_modulePtr->RegisterCaptureDataCallback(this);

    std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> devInfo(
                webrtc::VideoCaptureFactory::CreateDeviceInfo());

    devInfo->GetCapability(m_modulePtr->CurrentDeviceName(), 0, m_capability);
    m_capability.width = static_cast<int32_t>(iWidth);
    m_capability.height = static_cast<int32_t>(iHeight);
    m_capability.maxFPS = static_cast<int32_t>(iFPS);
    m_capability.videoType = webrtc::VideoType::kI420;

    if(m_modulePtr->StartCapture(m_capability) != 0)
    {
        destroy();
        return false;
    }

    return true;

}

void CameraVideoCapture::AddOrUpdateSink(
        VideoSinkInterface<webrtc::VideoFrame> *sink, const rtc::VideoSinkWants &wants)
{
    Q_UNUSED(sink);
    Q_UNUSED(wants);
    qDebug() << __func__;
}

void CameraVideoCapture::RemoveSink(VideoSinkInterface<webrtc::VideoFrame> *sink)
{
    Q_UNUSED(sink);
    qDebug() << __func__;
}

void CameraVideoCapture::OnFrame(const webrtc::VideoFrame &frame)
{
    Q_UNUSED(frame);
//    qDebug() << __func__;
}

void CameraVideoCapture::destroy()
{
    if(m_modulePtr.get() != nullptr)
    {
        m_modulePtr->StopCapture();
        m_modulePtr->DeRegisterCaptureDataCallback();
        m_modulePtr = nullptr;
    }
}
